package gui

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/widget"
	"github.com/sirupsen/logrus"
	"os"
	"path/filepath"
	"sort"
	"treesize/src/org/ligson/treesize/util"
)

var w fyne.Window

var myFileMap map[string]*util.MyFileInfo = make(map[string]*util.MyFileInfo)

var myFileTree *FileTree

var dirLabel *widget.Label = widget.NewLabel("")

func initFont() error {
	//fontFile := "./MONACO.TTF"
	fontFile := "./msyh.ttf"
	fontPath, e := filepath.Abs(fontFile)

	if e != nil {
		logrus.Error(e)
		return e
	}
	logrus.Info("字体路径:" + fontPath)
	err := os.Setenv("FYNE_FONT", fontPath)
	if err != nil {
		return err
	}
	return nil
}

func OpenWin(theme fyne.Theme) error {
	err := initFont()
	if err != nil {
		return err
	}

	a := app.New()

	a.Settings().SetTheme(theme)
	w = a.NewWindow("文件夹大小统计")

	w.Resize(fyne.Size{Width: 800, Height: 500})

	myFileTree = NewFileTree()

	var fileTypeMap map[string][]*util.MyFileInfo = make(map[string][]*util.MyFileInfo)
	//var fileTypes []string
	var fileTypeSize []FileTypeSize

	dlg := dialog.NewFolderOpen(func(uri fyne.ListableURI, err error) {
		if err != nil {
			logrus.Error(err.Error())
			return
		}
		if uri != nil {
			dirLabel.SetText(uri.Path())
			myFileMap = loadData(uri.Path(), myFileTree)
			for _, info := range myFileMap {
				if !info.File.IsDir() {
					arr := fileTypeMap[info.GetFileSuffix()]
					if arr == nil {
						//arr[0] = info
						arr = append(arr, info)
					} else {
						arr = append(arr, info)
					}
					fileTypeMap[info.GetFileSuffix()] = arr
				}
			}

			fileTypeSize = make([]FileTypeSize, len(fileTypeMap))
			for key, _ := range fileTypeMap {
				var size int64 = 0
				for _, info := range fileTypeMap[key] {
					if !info.File.IsDir() {
						size += info.File.Size()
					}
				}
				fileTypeSize = append(fileTypeSize, FileTypeSize{Type: key, Size: size})
				//fileTypes = append(fileTypes, key)
			}
			sort.Sort(FileTypeSizeSort(fileTypeSize))
		}

	}, w)

	btn := widget.NewButton("选择目录", func() {
		dlg.Show()
	})

	list := widget.NewList(
		func() int {
			return len(fileTypeMap)
		},
		func() fyne.CanvasObject {
			return NewListItemLabel("template")
		},
		func(i widget.ListItemID, o fyne.CanvasObject) {
			if len(fileTypeSize) > 0 {
				var suffix string = fileTypeSize[i].Type
				//o.(*widget.Label).SetText(suffix)
				o.(*ListItemLabel).UpdateText(suffix, fileTypeMap[suffix])
			}
		})

	layout := container.NewBorder(container.NewGridWithRows(2, btn, dirLabel), nil, nil, nil, container.NewHSplit(list, myFileTree))
	w.SetContent(layout)
	w.ShowAndRun()
	return nil
}
